/*
 * @Author: deng-chao
 * @Date: 2022-05-20 15:06:57
 * @LastEditTime: 2022-10-10 17:54:42
 * @Description: 用户信息
 */
import api from '@/api/index'

import {
  setUserInfo, getUserInfo, removeUserInfo,
  setToken, getToken, removeToken,
  setRefreshToken, getRefreshToken, removeRefreshToken,
  setOpenId, getOpenId, removeOpenId

} from "@/utils/storage";
// 初始状态
const state = {
  // 用户信息
  userInfo: getUserInfo(),
  // token 用户认证
  token: getToken(),
  // 刷新token
  refresh_token: getRefreshToken(),
  // 用户openId
  openId: getOpenId() || 'oCNrG6GrcmolUQQOYxcomwhukV_o',

  // 选择银行卡
  bankCard: false,
};

// 计算属性
const getters = {
  getUserInfo: (state) => state.userInfo ? JSON.parse(state.userInfo) : false,
  getOpenId: (state) => state.openId || false,
  getToken: (state) => state.token || false,
  getRefreshToken: state => state.refresh_token || false,

  getBankCard: state => state.bankCard || false,
};
// 同步
const mutations = {
  SET_USER_INFO(state, data) {
    setUserInfo(data)
    state.userInfo = data;
  },
  SET_OPEN_ID(state, data) {
    setOpenId(data);
    state.openId = data;
  },
  SET_TOKEN(state, data) {
    setToken(data)
    state.token = data;
  },
  SET_BANK_CARD(state, data) {
    state.bankCard = data;
  }
};
// 异步
const actions = {
  // 获取用户信息
  async GET_USER_INFO({
    commit
  }, data) {
    await new Promise(async (resolve, reject) => {
      try {
        let res = await api.user.getMemberDetail();
        console.log('userInfo', res)
        commit('SET_USER_INFO', JSON.stringify(res.data));
        return resolve(res)
      } catch (e) {
        console.error(e);
        return reject(e)
      }
    })

  },

  refreshToken({ commit }, data) {//刷新token
    if (!getRefreshToken()) return false;
    api.user.getRefreshToken({ token: getRefreshToken() }).then(e => {
      const { access_token, refresh_token } = e.data;
      setToken(access_token);
      setRefreshToken(refresh_token);
      commit("SET_TOKEN", access_token);
    })
  },
  setUserInfo({ commit }, data) {
    commit("SET_USER_INFO", JSON.stringify(data));
  },
  setOpenId({ commit }, data) {
    api.sys
      .getWxChatOpenId({ code: data })
      .then((res) => {
        if (res.code <= 10) {
          if (res.message) {
            commit("SET_OPEN_ID", res.message);
          }
        }
      });
  },
  setBankCard({ commit }, data) {
    commit("SET_BANK_CARD", data);
  },
  setToken({ commit }, data) {
    commit("SET_TOKEN", data);
  },
  // 清除用户信息
  removeUser({ commit }, data) {
    removeUserInfo();
    removeToken();
    removeRefreshToken();
    removeOpenId();
    commit("SET_USER_INFO", '');
    commit("SET_OPEN_ID", '');
    commit("SET_TOKEN", '');
  },
};
export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations,
};
